package com.ajc.seata.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @Author: AnJunchao
 * @Description:
 * @Date: Create in 2019-10-12 09:33:59
 * @Modified By:
 */
@Configuration
@EnableTransactionManagement
@DependsOn("transactionManager")
@EnableJpaRepositories(
        entityManagerFactoryRef="bank1ManagerFactory",//指明实体的管理Factory 名字在本类配置的LocalContainerEntityManagerFactoryBean
        transactionManagerRef="transactionManager",//这里注意了 这里的name就是上面DataSourceConfig这个类中事务管理器@Bean的name
        basePackages=  "com.ajc.seata.repository.bank1") //设置jta-bank1对应的Repository所在位置
public class Bank1Config {
  /**
   * 配置数据源 可以配置多个但必须用@Qualifier("xxx")指明
   * @return
   */
  @Primary//由多个数据源的时候 用这个指定默
  @Bean
  @ConfigurationProperties(prefix = "spring.jta.atomikos.datasource.jta-bank1") //以什么开头的spring文件中的配置路径
  @Qualifier("dataSourceJTABank1")
  public DataSource dataSourceJTABank1() {
    return new AtomikosDataSourceBean();
  }

  @Autowired
  JpaProperties jpaProperties;
  //*--------- atomikos -----------*//*
  @Primary //自动装配时当出现多个Bean候选者时，被注解为@Primary的Bean将作为首选者，否则将抛出异常
  @Bean(name = "bank1ManagerFactory")
  @DependsOn("transactionManager")
  public LocalContainerEntityManagerFactoryBean bannk1ManagerFactoryDemo(EntityManagerFactoryBuilder builder) {
    //如果在spring的配置文件中不指定这里可以用这种方式指明
    // jpaProperties.getProperties().put("hibernate.transaction.jta.platform", AtomikosJtaPlatform.class.getName());
    return builder
            .dataSource(dataSourceJTABank1())
            .properties(jpaProperties.getProperties())
            .packages("com.ajc.seata.entity.bank1") //设置实体类所在位置：类或包
            .persistenceUnit("jta-bank1") //持久化单元名称
            .build();
  }

}